package com.lanhai.agv.listener;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import com.lanhai.agv.queue.StationEventQueue;
import com.lanhai.agv.queue.StationEventUnit;

/** 
 * 收取来自对接设备的消息
 * @author virus408
 *
 */
public class StationListener {
  
	private boolean running;
	private Thread th;
	
	public void Start(int port) {
		running=true;
		th=new Thread() { 
			@Override
			public void run() {
				try{ 
					DatagramSocket	ds = new DatagramSocket(port);
					while(running){
						byte buf[] = new byte[20];
						DatagramPacket dp = new DatagramPacket(buf, buf.length);
						ds.receive(dp);
					 
						StationEventUnit unit=new StationEventUnit();
						unit.setData(buf);
						unit.setIp(dp.getAddress().getHostAddress());
						unit.setPort(dp.getPort());
						StationEventQueue.Push(unit);
					}	
					ds.close();
				}catch(Exception e){
					e.printStackTrace();
				}	
			}
			
		};
		th.start();
	}
	
	
	
	public void Stop() {
		running=false;
		try {
			th.interrupt();
			th=null; 
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
}
